package com.yx.frame.log;

import java.text.*;
import java.io.*;
import java.util.*;

public final class MessageLogServer extends Thread {
	private static MessageLogServer instance = null;
	private long refrshTime = 10 * 1000;
	private String logFileName = null;
	private Vector mesPool = new Vector();
	private int MaxLogLineNumber = 1000;
	private int MaxLogFileLineNumber = 100000;

	private MessageLogServer() {
		this.logFileName = LogFactory.SYSTEM_LOG_FILE_PATH;
		File logDir=new File(logFileName);
		if(!logDir.exists()){
			logDir.mkdir();
		}
	}

	public static MessageLogServer getInstance() {
		if (instance == null) {
			instance = new MessageLogServer();
			instance.start();
		}
		return instance;
	}

	public void run() {
		while (true) {
			synchronized (this) {
				try {
					wait(refrshTime);
				} catch (Exception e) {
				}
			}
			try {
				removeOldLogFiles();
			} catch (Throwable e) {
			}
			try {
				write(mesPool, getCurLogFileName());
			} catch (Exception e) {

			}
		}
	}

	public static Date getDateBefore(int day) {
		Calendar now = Calendar.getInstance();
		now.setTime(new Date());
		now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
		return now.getTime();
	}

	public void removeOldLogFiles() {
		String dateTimeToString = dateTimeToString(getDateBefore(30));
		String oldLogFile = this.logFileName + "server_" + dateTimeToString
				+ ".log";
		File file = new File(oldLogFile);
		if (file.exists()) {
			file.delete();
		}
	}

	public void sendMessage(String mes) {
		if (mesPool.size() < MaxLogLineNumber) {
			mesPool.addElement(mes);
		}
		synchronized (this) {
			this.notify();
		}
	}

	public String getLogFileName() {
		return logFileName;
	}

	private void write(Vector v, String fileName) {
		try {
			OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(fileName,true), "UTF-8");
			while (v.size() > 0) {
				String str = v.elementAt(0).toString();
				writer.write(str);
				v.remove(0);
				synchronized (this) {
					try {
						wait(50);
					} catch (Exception e) {
					}
				}
			}
			writer.close();
		} catch (Exception e) {
			return;
		}

	}

	private String getCurLogFileName() {
		return this.logFileName + "server_" + dateTimeToString(new Date())
				+ ".log";
	}

	private static String dateTimeToString(java.util.Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd-HH");
		try {
			return formatter.format(date);
		} catch (Exception e) {
			return date.toString();
		}
	}

	public static void main(String[] args) {
		String dateTimeToString = dateTimeToString(getDateBefore(30));
		System.out.println(dateTimeToString);
	}

}
